import logging, socket

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect

from clustermanager.lib.base import BaseController, render

log = logging.getLogger(__name__)

class HostController(BaseController):

    def index(self):
        # Return a rendered template
        return render('/host/host.mako')

    def list(self):
        c.hosts=(
            '192.168.3.10',
            '192.168.3.211',
            '192.168.3.124',
            '192.168.3.212',
            '172.16.0.10'
            
        )
#        for host in hosts:
#            print(host)
#        c.host='aaaaaaaaaa'
        return render('/host/host.list.mako')
    def view(self, id):
        if id is None:
            host=''
        else:
            host=id

        if host:
            HOST, PORT = host, 7800
            CRLF="\r\n"
            data = "help".join(CRLF)
            # Create a socket (SOCK_STREAM means a TCP socket)
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            # Connect to server and send data
            sock.connect((HOST, PORT))
            #sock.send(data)
            sock.send("help\r\n")
            # Receive data from the server and shut down
            received = ''
            while 1:
                data = sock.recv(1024)
                if not data: 
                    break
                else:
                    received += data
            sock.close()

            c.host = HOST
            c.protos = received.split("\r\n")[1:]
            return render('/host/host.view.mako')
        else:
            print (":(") 
    def execute(self, id):
        host,proto = id.split("|")
        HOST, PORT = host, 7800
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((HOST, PORT))
        sock.send(proto + "\r\n")
        received = ''
        while 1:
            data = sock.recv(1024)
            if not data:
                break
            else:
                received += data
        sock.close()
        c.result = received
        c.host = host
        return render('/host/host.execute.mako')
